<?php
/**
 * 毛文科
 */
namespace tenxun\bind\weixin;
use tenxun\bind\Config;
use tenxun\src\Curl;
use think\facade\Cache;

class WeiXinFenXiang extends Config
{
    protected $access_token = '';
    public function setAccessToken($access_token){
        $this->access_token = $access_token;
        return $this;
    }

    /**获取access_token
     * @param string $type
     * @return mixed
     */
    public function getAccessToken($type='access_token'){
        if(!$access_token = Cache::get($type)){
         $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->getAppId().'&secret='.$this->appsecret;
         $obj = new Curl();
         $array = $obj->fasong($url,1)->jsonToArray();
         if($array['access_token']??null){
             $access_token = $array['access_token'];
             Cache::set($type,$access_token,7100);
         }else{
             exception('没有获取到access_token',400);
         }
        }
        return $access_token;
    }

    /**获取jsapi_ticket
     * @param string $type
     * @return mixed
     * @throws \Exception
     */
    public function getJsapiTicket($type='jsapi_ticket'){
        if(!$jsapi_ticket= Cache::get($type)){
            $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$this->getAccessToken().'&type=jsapi';
            $obj = new Curl();
            $array = $obj->fasong($url,1)->jsonToArray();
            if($array['ticket']??null){
                $jsapi_ticket = $array['ticket'];
            }else{
                exception('没有获取到jsapi_ticket',400);
            }
        }
        return $jsapi_ticket;
    }

    /**获取权限注入
     * @param null $noncestr
     * @param null $timestamp
     * @return mixed
     * @throws \Exception
     */
    public function getConfig($noncestr=null,$timestamp=null){
        $data['url'] = request()->url();
        if(!$noncestr){
            $data['noncestr'] = uniqid();
        }
        if(!$timestamp){
            $data['timestamp'] = time();
        }
        $data['jsapi_ticket'] = $this->getJsapiTicket();
        ksort($data);
        $str = '';
        foreach ($data as $key=>$value){
            $str .=$key.'='.$value;
        }
        $data['signature'] =sha1($str);
        return $data;
    }
}